<?php

/**
 * 模块权限验证中间件
 *
 */

namespace App\Http\Middleware;

use App\Helpers\JwtUtils;
use App\Models\UserModel;
use App\Services\DataPermissionService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Validation\UnauthorizedException;

class ModuleAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $authorization = $request->header('Authorization', '');
        if (empty($authorization)) {
            $authorization = $request->get('Authorization', '');
        }
        if (empty($authorization)) {
            throw new \Exception('Authorization 为空');
        }
        $userId = JwtUtils::getUserId();
        if (!$userId) {
            throw new UnauthorizedException('用户信息不存在');
        }
        $user = UserModel::find($userId);
        if (empty($user)) {
            throw new UnauthorizedException('用户信息不存在');
        }

        // 数据权限验证
        $service = new DataPermissionService($userId);
        $service->check();

        register('user_id', $userId);
        register('user', $user);
        return $next($request);
    }
}
